//
//  DAWebFileViewController.m
//  DAKnowledge
//
//  Created by DACadmin on 16/7/19.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DAWebFileViewController.h"
#import <WebKit/WebKit.h>
#import <UIKit/UIKit.h>
#import <QuickLook/QuickLook.h>

@interface DAWebFileViewController ()<WKNavigationDelegate,QLPreviewControllerDataSource>{
    
}
@property (nonatomic, strong) WKWebView *fileView;
@property (nonatomic, strong) QLPreviewController *previewController;
@property (nonatomic, copy) NSString *filePath;
@property (nonatomic, assign) BOOL isFinish;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) UIImage *image;
@property (nonatomic) BOOL isCollected;

@end
@implementation DAWebFileViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatPreview];
    self.isCollected = [[DACollectionFiles shareDACollectionFiles]isContainCollectionsWith:self.fileID];
    [self collectImage];
    
}
//进入页面   加载是否收藏  图片
- (void)collectImage{
    if(self.isCollected){
        self.image = [UIImage imageNamed:@"collected"];
    }else{
        self.image = [UIImage imageNamed:@"discollect"];
    }
    self.image  = [self.image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:self.image style:UIBarButtonItemStylePlain target:self action:@selector(touchImage)];
}

- (void)touchImage{
    //点击图片  如果是  已收藏则  取消收藏
    if (self.isCollected) {
        NSDictionary *dic;
        NSString *url = DACancelCollectionFile;
        dic = @{@"collectUserID":self.userID , @"collectFolderName":self.filefolderName};
        [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
            if (result) {
               // NSLog(@"结果 %@",result);
                [SVProgressHUD showSuccessWithStatus:@"取消收藏成功"];
                [[DACollectionFiles shareDACollectionFiles] updateWithUserID:self.userID Block:^(NSMutableArray *array) {
                    self.isCollected = NO;
                    [self collectImage];
                }];
            }else{
                [SVProgressHUD showErrorWithStatus:@"取消收藏失败"];
            }
        }];
    }
    //如果没收藏  则收藏
    else{
        NSDictionary *dic;
        NSString *url = DACollectionFile;
        dic = @{@"collectUserID":self.userID , @"collectFolderName":self.filefolderName};
        [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
            if (result) {
               // NSLog(@"结果 %@",result);
                [SVProgressHUD showSuccessWithStatus:@"收藏成功"];
                [[DACollectionFiles shareDACollectionFiles] updateWithUserID:self.userID Block:^(NSMutableArray *array) {
                    self.isCollected = YES;
                    [self collectImage];
                }];
            }else{
                [SVProgressHUD showErrorWithStatus:@"收藏失败"];
            }
        }];
    }
}

- (void)creatPreview{
    //打开显示文件
    self.previewController = [[QLPreviewController alloc]init];
    self.previewController.dataSource =self;
    self.previewController.view.frame=self.view.bounds;
    
    // [self presentViewController:self.previewController animated:YES completion:nil];
    // [self.navigationController addChildViewController:self.previewController];
    [self.view addSubview:self.previewController.view];
    //[self.view addSubview:self.fileView];

}
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller
{
    return 1;
}

- (id <QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
{
    //NSString *path = [[NSBundle mainBundle] pathForResource:@"777" ofType:@"docx"];//需要在线预览的文件
    return [NSURL fileURLWithPath:self.fileUrl];
}

//下载文件
//- (void)downLoadFile:(NSString *)fileName saveInPath:(NSString *)path fromURL:(NSURL *)url{
   //
    //AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
   // NSString  *fullPath = [NSString stringWithFormat:@"%@/%@", path, fileName];
    // NSURL *url = [NSURL URLWithString:@"http://www.abc.com/test.mp4"];
  //  NSURLRequest *request = [NSURLRequest requestWithURL:url];
   // NSURLSessionDownloadTask *task =
    //    [manager downloadTaskWithRequest:request
    //                            progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    //                                return [NSURL fileURLWithPath:fullPath];
    //                            }
    //                   completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    //
    //                   }];

  //  [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
       
    //        CGFloat count = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
        
    
        //        //[SVProgressHUD showProgress:count];
        //        NSString *str = [NSString stringWithFormat:@"%.2f%%", count * 100];
        //        [SVProgressHUD showProgress:count status:str];
        
        
        //  [downloadProgress addObserver:self forKeyPath:@"fractionCompleted"options:NSKeyValueObservingOptionNew context:NULL];
       // dispatch_async(dispatch_get_main_queue(), ^{
   //     if (self.isFinish == NO) {
      //      [SVProgressHUD  showProgress:count];
    //    }
        
        //[SVProgressHUD showProgress:count status:@"正在下载.."];
       // [MBProgressHUD HUDForView:self.view].progress = count;
      //  });
        
        //NSLog(@"%@", downloadProgress);
       // NSLog(@"正在下载");
        
   // } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
    //    return [NSURL fileURLWithPath:fullPath];
 //   } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        //NSLog(@"下载完成");
        //[SVProgressHUD showWithStatus:@"下载完成"];
     //   [SVProgressHUD dismiss];
       // [self creatPreview];
  //  }];
   //[task resume];
//}


//- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
//    NSProgress *progress = (NSProgress *)object;
//    CGFloat count = progress.fractionCompleted;
//    NSString *str = [[NSString alloc]init];
//    if ([keyPath isEqualToString:@"fractionCompleted"] && [object isKindOfClass:[NSProgress class]]) {
//        NSLog(@"%@", progress);
//        NSLog(@"%f", count);
//        str = [NSString stringWithFormat:@"%.0f%%", count * 100];
//        NSLog(@"%@", str);
//    }
//    //[SVProgressHUD showProgress:count status:str];
//}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
